import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';

class SalesAnalyticsSection extends StatefulWidget {
  const SalesAnalyticsSection({Key? key}) : super(key: key);

  @override
  State<SalesAnalyticsSection> createState() => _SalesAnalyticsSectionState();
}

class _SalesAnalyticsSectionState extends State<SalesAnalyticsSection> {
  String _selectedDateRange = 'today';
  String _selectedChartType = 'daily';
  bool _showPercentages = false;

  // ۋاقىتلىق ئانالىز مەلۇماتلىرى (كېيىن مەلۇمات ئامبىرىدىن ئېلىنىدۇ)
  final Map<String, double> _salesByCategory = {
    'مېۋە': 2500.00,
    'كۆكتات': 1800.50,
    'گۆش': 3200.75,
    'سۈت مەھسۇلاتلىرى': 1200.25,
    'ئىچىملىك': 800.50,
  };

  final List<DailySales> _dailySales = [
    DailySales(date: DateTime.now().subtract(const Duration(days: 6)), amount: 850.00),
    DailySales(date: DateTime.now().subtract(const Duration(days: 5)), amount: 920.50),
    DailySales(date: DateTime.now().subtract(const Duration(days: 4)), amount: 780.25),
    DailySales(date: DateTime.now().subtract(const Duration(days: 3)), amount: 1100.75),
    DailySales(date: DateTime.now().subtract(const Duration(days: 2)), amount: 950.00),
    DailySales(date: DateTime.now().subtract(const Duration(days: 1)), amount: 1250.25),
    DailySales(date: DateTime.now(), amount: 890.50),
  ];

  final List<TopProduct> _topProducts = [
    TopProduct(name: 'ئالما', quantity: 150, revenue: 899.50),
    TopProduct(name: 'ئۈزۈم', quantity: 120, revenue: 1079.80),
    TopProduct(name: 'پىياز', quantity: 200, revenue: 798.00),
    TopProduct(name: 'گۆش', quantity: 80, revenue: 1600.00),
    TopProduct(name: 'سۈت', quantity: 100, revenue: 500.00),
  ];

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Expanded(
                child: DropdownButtonFormField<String>(
                  value: _selectedDateRange,
                  decoration: InputDecoration(
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  items: const [
                    DropdownMenuItem(value: 'today', child: Text('بۈگۈن')),
                    DropdownMenuItem(value: 'week', child: Text('بۇ ھەپتە')),
                    DropdownMenuItem(value: 'month', child: Text('بۇ ئاي')),
                    DropdownMenuItem(value: 'year', child: Text('بۇ يىل')),
                  ],
                  onChanged: (value) {
                    if (value != null) {
                      setState(() => _selectedDateRange = value);
                    }
                  },
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: DropdownButtonFormField<String>(
                  value: _selectedChartType,
                  decoration: InputDecoration(
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  items: const [
                    DropdownMenuItem(value: 'daily', child: Text('كۈنلۈك سودا')),
                    DropdownMenuItem(value: 'category', child: Text('تۈر بويىچە')),
                  ],
                  onChanged: (value) {
                    if (value != null) {
                      setState(() => _selectedChartType = value);
                    }
                  },
                ),
              ),
            ],
          ),
          const SizedBox(height: 24),

          SizedBox(
            height: 100,
            child: Row(
              children: [
                _buildStatCard(
                  title: 'جەمئىي سودا',
                  value: '¥7,500.25',
                  change: '+12.5%',
                  icon: Icons.attach_money,
                  color: Colors.green,
                ),
                const SizedBox(width: 16),
                _buildStatCard(
                  title: 'سودا سانى',
                  value: '125',
                  change: '+8.3%',
                  icon: Icons.shopping_cart,
                  color: Colors.blue,
                ),
                const SizedBox(width: 16),
                _buildStatCard(
                  title: 'ئوتتۇرىچە سودا',
                  value: '¥60.00',
                  change: '+4.2%',
                  icon: Icons.analytics,
                  color: Colors.orange,
                ),
              ],
            ),
          ),
          const SizedBox(height: 24),

          Expanded(
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  flex: 2,
                  child: Card(
                    child: Padding(
                      padding: const EdgeInsets.all(16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                _selectedChartType == 'daily' ? 'كۈنلۈك سودا ئەھۋالى' : 'تۈر بويىچە سودا',
                                style: const TextStyle(
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              if (_selectedChartType == 'category')
                                Row(
                                  children: [
                                    const Text('پىرسەنت كۆرسىتىش'),
                                    Switch(
                                      value: _showPercentages,
                                      onChanged: (value) {
                                        setState(() => _showPercentages = value);
                                      },
                                    ),
                                  ],
                                ),
                            ],
                          ),
                          const SizedBox(height: 16),
                          Expanded(
                            child: _selectedChartType == 'daily'
                                ? _buildDailySalesChart()
                                : _buildCategorySalesChart(),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: Card(
                    child: Padding(
                      padding: const EdgeInsets.all(16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Text(
                            'ئەڭ كۆپ سېتىلغان مەھسۇلاتلار',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 16),
                          Expanded(
                            child: ListView.builder(
                              itemCount: _topProducts.length,
                              itemBuilder: (context, index) {
                                final product = _topProducts[index];
                                return ListTile(
                                  title: Text(product.name),
                                  subtitle: Text(
                                    '${product.quantity} دانە - ¥${product.revenue.toStringAsFixed(2)}',
                                  ),
                                  leading: CircleAvatar(
                                    backgroundColor: Colors.orange.shade100,
                                    child: Text(
                                      '${index + 1}',
                                      style: TextStyle(
                                        color: Colors.orange.shade900,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ),
                                );
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStatCard({
    required String title,
    required String value,
    required String change,
    required IconData icon,
    required Color color,
  }) {
    final isPositive = !change.startsWith('-');
    return Expanded(
      child: Card(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Icon(icon, color: color),
                  const SizedBox(width: 8),
                  Text(
                    title,
                    style: const TextStyle(
                      color: Colors.grey,
                      fontSize: 14,
                    ),
                  ),
                ],
              ),
              const Spacer(),
              Text(
                value,
                style: const TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 4),
              Row(
                children: [
                  Icon(
                    isPositive ? Icons.arrow_upward : Icons.arrow_downward,
                    size: 14,
                    color: isPositive ? Colors.green : Colors.red,
                  ),
                  const SizedBox(width: 4),
                  Text(
                    change,
                    style: TextStyle(
                      color: isPositive ? Colors.green : Colors.red,
                      fontSize: 12,
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildDailySalesChart() {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: LineChart(
        LineChartData(
          gridData: const FlGridData(show: false),
          titlesData: FlTitlesData(
            leftTitles: const AxisTitles(
              sideTitles: SideTitles(
                showTitles: true,
                reservedSize: 40,
              ),
            ),
            bottomTitles: AxisTitles(
              sideTitles: SideTitles(
                showTitles: true,
                getTitlesWidget: (value, meta) {
                  if (value.toInt() >= 0 && value.toInt() < _dailySales.length) {
                    final date = _dailySales[value.toInt()].date;
                    return Padding(
                      padding: const EdgeInsets.only(top: 8),
                      child: Text(
                        '${date.month}/${date.day}',
                        style: const TextStyle(fontSize: 12),
                      ),
                    );
                  }
                  return const Text('');
                },
                reservedSize: 30,
              ),
            ),
            rightTitles: const AxisTitles(
              sideTitles: SideTitles(showTitles: false),
            ),
            topTitles: const AxisTitles(
              sideTitles: SideTitles(showTitles: false),
            ),
          ),
          borderData: FlBorderData(
            show: true,
            border: Border.all(color: Colors.grey.shade300),
          ),
          minX: 0,
          maxX: (_dailySales.length - 1).toDouble(),
          minY: 0,
          maxY: _dailySales.map((e) => e.amount).reduce((a, b) => a > b ? a : b) * 1.2,
          lineBarsData: [
            LineChartBarData(
              spots: _dailySales.asMap().entries.map((entry) {
                return FlSpot(entry.key.toDouble(), entry.value.amount);
              }).toList(),
              isCurved: true,
              color: Colors.orange,
              barWidth: 3,
              isStrokeCapRound: true,
              dotData: const FlDotData(show: true),
              belowBarData: BarAreaData(
                show: true,
                color: Colors.orange.withOpacity(0.2),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCategorySalesChart() {
    final total = _salesByCategory.values.reduce((a, b) => a + b);
    final sections = _salesByCategory.entries.map((entry) {
      final percentage = (entry.value / total * 100).toStringAsFixed(1);
      return PieChartSectionData(
        color: _getCategoryColor(entry.key),
        value: entry.value,
        title: _showPercentages ? '$percentage%' : '¥${entry.value.toStringAsFixed(0)}',
        radius: 100,
        titleStyle: const TextStyle(
          fontSize: 12,
          fontWeight: FontWeight.bold,
          color: Colors.white,
        ),
      );
    }).toList();

    return Row(
      children: [
        Expanded(
          child: PieChart(
            PieChartData(
              sections: sections,
              centerSpaceRadius: 40,
              sectionsSpace: 2,
            ),
          ),
        ),
        const SizedBox(width: 16),
        SizedBox(
          width: 140,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: _salesByCategory.entries.map((entry) {
              return Padding(
                padding: const EdgeInsets.symmetric(vertical: 4),
                child: Row(
                  children: [
                    Container(
                      width: 12,
                      height: 12,
                      decoration: BoxDecoration(
                        color: _getCategoryColor(entry.key),
                        shape: BoxShape.circle,
                      ),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        entry.key,
                        style: const TextStyle(fontSize: 12),
                      ),
                    ),
                  ],
                ),
              );
            }).toList(),
          ),
        ),
      ],
    );
  }

  Color _getCategoryColor(String category) {
    final colors = [
      Colors.orange,
      Colors.blue,
      Colors.green,
      Colors.red,
      Colors.purple,
      Colors.teal,
      Colors.pink,
      Colors.indigo,
    ];

    return colors[_salesByCategory.keys.toList().indexOf(category) % colors.length];
  }
}

class DailySales {
  final DateTime date;
  final double amount;

  DailySales({
    required this.date,
    required this.amount,
  });
}

class TopProduct {
  final String name;
  final int quantity;
  final double revenue;

  TopProduct({
    required this.name,
    required this.quantity,
    required this.revenue,
  });
} 